import axios, { AxiosInstance } from 'axios'
import _ from 'lodash'
import MockAdapter from 'axios-mock-adapter'

/**
 * axios-mock-adapter 应用 --- 仅限 `__mock__` 中使用
 * @link https://github.com/ctimmerm/axios-mock-adapter#example
 * @example
 * axiosMock('default', mock => {
 *   mock.onGet('/xxx').reply(
 *     delayFn(600, () => ({
 *       code: '0',
 *     })),
 *   )
 * })
 */
export const axiosMock = (
  axiosInstance: AxiosInstance | AxiosInstance[] | 'default',
  mockFn: (mock: MockAdapter) => void,
): void => {
  const instances = [axiosInstance === 'default' ? axios : axiosInstance].flat() as Array<
    AxiosInstance & { $_mock?: MockAdapter }
  >

  instances.forEach(instance => {
    let mock: MockAdapter

    // 已有实例
    if (instance.$_mock) {
      mock = instance.$_mock
    }
    // 创建实例
    {
      mock = new MockAdapter(instance, { onNoMatch: 'passthrough' })
      mock.restore = _.wrap(mock.restore, oldRestore => {
        delete instance.$_mock
        oldRestore.call(mock)
      })
      instance.$_mock = mock
    }

    mockFn(mock)
  })
}
